package com.zuoyi.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.zuoyi.io.Resources;
import com.zuoyi.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     *该方法就是解析配置文件，并且封装到Configuration中
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        // 解析输入流 → 通过dom4j包中的SAXReader类对读取出来字节输入流进行解析
        Document document = new SAXReader().read(inputStream);
        /**
         * 通过//这种表示方法，不论property属性在xml文件中的哪一级都可以直接读取到
         * selectNodes():获取标签
         * attributeValue():获取标签的属性值
         */
        Element rootElement = document.getRootElement();
        List<Element> elements = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : elements) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }

        // 设置数据源  ComboPooledDataSource是数据库连接池对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);

        //解析mapper.xml  拿到路径 → 通过路径将配置文件加载成字节输入流 → 再用dom4j进行解析
        List<Element> mapperElements = rootElement.selectNodes("//mapper");
        for (Element mapperElement : mapperElements) {
            String mapperPath = mapperElement.attributeValue("resource");
            InputStream resourcesAsSteam = Resources.getResourcesAsSteam(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourcesAsSteam);
        }


        return configuration;
    }
}
